package readHandle

import (
	"chart.zozoo.net/app/dao/messageHistoryDao"
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/app/socket/connManage"
	"chart.zozoo.net/core/myRedis"
	"encoding/json"
	"fmt"
)

//清理聊天列表未读消息

type Unread struct {
	Uuid string `json:"uuid"`
}

func handleCleanUnread(msg string, addr string) {
	//将消息转换为对象
	unread := &Unread{}
	err := json.Unmarshal([]byte(msg), unread)
	if err != nil {
		fmt.Println("字符换转对象失败 err:", err)
		return
	}

	//发送用户信息
	user := connManage.GetConn(addr).UserInfo

	//记录缓存
	myHashKey := GetMessageHistoryCacheKey(user.Id)
	cmd := myRedis.RedisClient.HGet(myHashKey, unread.Uuid)
	history := new(models.MessageHistory)

	//修改状态
	change := false
	if cmd.Err() == nil {
		//存在缓存，将缓存转换为对象，再修改对象，再保存缓存
		err = json.Unmarshal([]byte(cmd.Val()), history)
		if err != nil {
			return
		}

		//定义未读消息数量
		history.UnreadNum = 0

		//保存数据库
		if err = messageHistoryDao.UpdateById(
			history.Id,
			map[string]interface{}{
				"unread_num": history.UnreadNum,
			},
		); err != nil {
			return
		}

		change = true
	} else {
		//缓存不存在，查询数据库
		if history, err = messageHistoryDao.GetByUuid(user.Id, unread.Uuid); err != nil {
			return
		}

		if history.Id > 0 {
			//存在数据,修改
			history.UnreadNum = 0
			if err = messageHistoryDao.UpdateById(history.Id, map[string]interface{}{
				"unread_num": history.UnreadNum,
			}); err != nil {
				return
			}

			change = true
		}
	}

	//保存缓存
	if change {
		str, err := json.Marshal(history)
		if err != nil {
			return
		}
		myRedis.RedisClient.HSet(myHashKey, unread.Uuid, string(str))
	}
}
